package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.ImagePublishAdapter;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.ImageItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.CustomConstants;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.IntentConstants;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.YearMonthDayPicker2;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.R;

public class PublishActivity extends BaseActivity {
  private GridView mGridView;
  private ImagePublishAdapter mAdapter;
  private TextView sendTv, cancelTv, tv_choosedate;
  private View rel_choosedate;
  @InjectView(id = R.id.edit_box)
  private EditText edit_box;

  public static List<ImageItem> mDataList = new ArrayList<ImageItem>();

  private static final int TAKE_PICTURE = 0x000000;
  private String selectDateString;
  private String jsonUrl = "[";
  private String path = "";
  int total;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_publish);

    hideTitleView();

    initData();
    initView();
  }

  @Override
  protected void onNewIntent(Intent intent) {
    setIntent(intent);
    processExtraData();
    super.onNewIntent(intent);
  }

  @Override
  protected void onDestroy() {
    Intent resultIntent = new Intent();
    setResult(RESULT_CANCELED, resultIntent);

    finish();

    super.onDestroy();
  }

  @SuppressWarnings("unchecked")
  private void processExtraData() {
    Intent intent = getIntent();
    if (intent != null) {
      getTempFromPref();
      List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
          .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
      if (incomingDataList != null) {
        mDataList.addAll(incomingDataList);
      }
      if (mAdapter != null && mDataList != null && !mDataList.isEmpty()) {
        mAdapter.updateData(mDataList);
      }
    }
  }

  @Override
  protected void onPause() {
    super.onPause();
    saveTempToPref();
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveTempToPref();
  }

  private void saveTempToPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    String prefStr = JSON.toJSONString(mDataList);
    sp.edit().putString(CustomConstants.PREF_TEMP_IMAGES, prefStr).commit();

  }

  private void getTempFromPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    String prefStr = sp.getString(CustomConstants.PREF_TEMP_IMAGES, null);
    if (!TextUtils.isEmpty(prefStr)) {
      List<ImageItem> tempImages = JSON.parseArray(prefStr, ImageItem.class);
      mDataList = tempImages;
    }
  }

  private void removeTempFromPref() {
    SharedPreferences sp = getSharedPreferences(
        CustomConstants.APPLICATION_NAME, MODE_PRIVATE);
    sp.edit().remove(CustomConstants.PREF_TEMP_IMAGES).commit();
  }

  @SuppressWarnings("unchecked")
  private void initData() {
    getTempFromPref();
    List<ImageItem> incomingDataList = (List<ImageItem>) getIntent()
        .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
    if (incomingDataList != null) {
      mDataList.addAll(incomingDataList);
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    notifyDataChanged(); // 当在ImageZoomActivity中删除图片时，返回这里需要刷新
  }

  // JSONArray jsListArray = new JSONArray();

  @SuppressLint("SimpleDateFormat")
  public void initView() {
    rel_choosedate = findViewById(R.id.rel_choosedate);
    rel_choosedate.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        final YearMonthDayPicker2 picker = new YearMonthDayPicker2(
            PublishActivity.this);
        picker.build(new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            selectDateString = picker.getSelectDateString();
            tv_choosedate.setText(picker.getSelectedDate2());
          }
        }, null);
        picker.show();

      }
    });

    mGridView = (GridView) findViewById(R.id.gridview);
    mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
    mAdapter = new ImagePublishAdapter(this, mDataList);
    mGridView.setAdapter(mAdapter);
    mGridView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position,
          long id) {
        if (position == getDataSize()) {
          Intent intent = new Intent(PublishActivity.this,
              ImageBucketChooseActivity.class);
          intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
              getAvailableSize());
          startActivity(intent);
        } else {
          Intent intent = new Intent(PublishActivity.this,
              ImageZoomActivity.class);
          intent.putExtra(IntentConstants.EXTRA_IMAGE_LIST,
              (Serializable) mDataList);
          intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
          startActivity(intent);
        }
      }
    });

    sendTv = (TextView) findViewById(R.id.tv_publish);
    cancelTv = (TextView) findViewById(R.id.tv_cancel);
    tv_choosedate = (TextView) findViewById(R.id.tv_choosedate);

    Calendar calendar = Calendar.getInstance();
    String created = calendar.get(Calendar.YEAR) + "年"
        + (calendar.get(Calendar.MONTH) + 1) + "月"// 从0计算
        + calendar.get(Calendar.DAY_OF_MONTH) + "日";
    tv_choosedate.setText(created);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    selectDateString = sdf.format(calendar.getTime());

    sendTv.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        removeTempFromPref();

        if (mDataList == null || mDataList.isEmpty()) {
          return;
        }

        showloading("");

        for (final ImageItem item : mDataList) {
          new CustomAsyncTask(PublishActivity.this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity,
                final ResponseResult result) {
              if (result != null && result.isSuccess()) {
                ++total;
                jsonUrl += "\"" + result.data + "\"" + ",";

                // JSONObject oTemp;
                // try {
                // oTemp = new JSONObject("\"" + result.data + "\"");
                // jsListArray.put(oTemp);
                // } catch (JSONException e) {
                // e.printStackTrace();
                // }

                if (total == mDataList.size()) {
                  jsonUrl = jsonUrl.substring(0, jsonUrl.length() - 1) + "]";

                  Async
                      .start(new Func0<ResponseResult>() {
                        @Override
                        public ResponseResult call() {
                          LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                          HashMap<String, Object> param_ = new HashMap<String, Object>();

                          // object = new JSONArray(jsonUrl);
                          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                          param_.put("urls", jsonUrl);

                          if (Tools.isNotEmpty(edit_box.getText().toString())) {
                            param_.put("title", edit_box.getText().toString());
                          }
                          param_.put("shoot", selectDateString);

                          return HttpUtils.startRequest(HttpUtils.API_URL
                              + "/api/2.0/member/photocloud", param_,
                              HttpUtils.TAG_POST_REQUEST);

                        }
                      }).subscribeOn(Schedulers.io())
                      .observeOn(AndroidSchedulers.mainThread())
                      .filter(new Func1<ResponseResult, Boolean>() {
                        @Override
                        public Boolean call(ResponseResult arg0) {
                          boolean r = (arg0 != null && Tools.isNotEmpty(arg0) && arg0
                              .isSuccess());
                          if (!r) {
                            // toastShow(/* "获取系统信息失败" */arg0.data);
                          }
                          return r;
                        }
                      }).doOnCompleted(new Action0() {

                        @Override
                        public void call() {
                          // dismissLoading();
                        }
                      }).subscribe(new Action1<ResponseResult>() {

                        @Override
                        public void call(ResponseResult arg0) {
                          runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                              if (Tools.isNotEmpty(edit_box.getText()
                                  .toString())) {

                                // TODO

                                // new CustomAsyncTask(PublishActivity.this,
                                // new IAsyncTask() {
                                // @Override
                                // public void onRecieveData(
                                // Activity activity,
                                // final ResponseResult arg0) {
                                //
                                // if (arg0.isSuccess()) {
                                // //
                                // } else {
                                // toastShow(arg0.data);
                                // }
                                //
                                // dismissLoading();
                                //
                                // }
                                //
                                // @Override
                                // public ResponseResult doInbackground(
                                // Activity activity) {
                                // LeUser lu = LeXiaoXiaoBanApp
                                // .getInstance().getUser();
                                // if (lu == null) {
                                // lu = Tools.restoreLeUser();
                                // }
                                //
                                // HashMap<String, Object> param_ = new
                                // HashMap<String, Object>();
                                // param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                                // param_.put("title", edit_box.getText()
                                // .toString());
                                //
                                // return HttpUtils.startRequest(
                                // HttpUtils.API_URL
                                // + "/api/2.0/member/photocloud/"
                                // + albumId, param_,
                                // HttpUtils.TAG_PUT_REQUEST);
                                // }
                                // }).execute();
                              }

                              dismissLoading();
                              toastShow("上传完毕!");

                              Intent resultIntent = new Intent();
                              setResult(RESULT_OK, resultIntent);

                              finish();
                            }
                          });
                        }
                      });
                }
              }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
              LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
              HashMap<String, Object> param_ = new HashMap<String, Object>();
              param_.put(HttpUtils.TAG_MOBILE_I, lu.id);
              param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
              param_.put(HttpUtils.TAG_MODULE_I, "member/photocloud");

              return HttpUtils.startUploadRequest(HttpUtils.API_URL
                  + HttpUtils.UPLOAD_BABY_AVATAR_POST, param_, "Filedata",
                  item.sourcePath, HttpUtils.TAG_POST_REQUEST);

            }
          }).execute("请检查网络连接!");
        }

      }
    });

    cancelTv.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        if (mDataList != null && !mDataList.isEmpty()) {
          CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
              PublishActivity.this).setMessage("您已经进行了修改，确认放弃本次修改吗？")
              .setTitle("提示")
              .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                  finish();
                }
              })
              .setPositiveButton("继续编辑", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                  dialog.dismiss();
                }
              });
          cdb.create().show();
        } else {
          finish();
        }
      }
    });
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && mDataList != null
        && !mDataList.isEmpty()) {
      CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
          PublishActivity.this).setMessage("您已经进行了修改，确认放弃本次修改吗？")
          .setTitle("提示")
          .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
              finish();
            }
          }).setPositiveButton("继续编辑", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
              dialog.dismiss();
            }
          });
      cdb.create().show();

      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  private int getDataSize() {
    return mDataList == null ? 0 : mDataList.size();
  }

  private int getAvailableSize() {
    int availSize = CustomConstants.MAX_IMAGE_SIZE - mDataList.size();
    if (availSize >= 0) {
      return availSize;
    }
    return 0;
  }

  // public String getString(String s) {
  // String path = null;
  // if (s == null)
  // return "";
  // for (int i = s.length() - 1; i > 0; i++) {
  // s.charAt(i);
  // }
  // return path;
  // }

  // public void takePhoto() {
  // Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  //
  // File vFile = new File(Environment.getExternalStorageDirectory()
  // + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
  // if (!vFile.exists()) {
  // File vDirPath = vFile.getParentFile();
  // vDirPath.mkdirs();
  // } else {
  // if (vFile.exists()) {
  // vFile.delete();
  // }
  // }
  // path = vFile.getPath();
  // Uri cameraUri = Uri.fromFile(vFile);
  // openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
  // startActivityForResult(openCameraIntent, TAKE_PICTURE);
  // }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case TAKE_PICTURE:
      if (mDataList.size() < CustomConstants.MAX_IMAGE_SIZE && resultCode == -1
          && !TextUtils.isEmpty(path)) {
        ImageItem item = new ImageItem();
        item.sourcePath = path;
        mDataList.add(item);
      }
      break;
    }
  }

  private void notifyDataChanged() {
    mAdapter.notifyDataSetChanged();
  }
}